package com.kgc.web;

import com.kgc.dao.AdminDao;
import com.kgc.entity.Admin;
import com.kgc.entity.AdminDesc;
import com.kgc.untils.CodecUtils;
import com.kgc.vo.R;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(name = "AdminServlet", value = "/AdminServlet")
public class AdminServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String opt = request.getParameter("opt");
        HttpSession session = request.getSession();
        PrintWriter writer = response.getWriter();
        AdminDao adminDao = new AdminDao();

        //验证码
        if ("total".equals(opt)) {
            int totalUser = adminDao.totalUser();
            request.setAttribute("totalUser", totalUser);
            int totalGongGao = adminDao.totalGongGao();
            request.setAttribute("totalGongGao", totalGongGao);
            int totalTouSu = adminDao.totalTouSu();
            request.setAttribute("totalTouSu", totalTouSu);
            int totalRepair = adminDao.totalRepair();
            request.setAttribute("totalRepair", totalRepair);
            int totalRoom = adminDao.totalRoom();
            request.setAttribute("totalRoom", totalRoom);
            int totalFreeRoom = adminDao.totalFreeRoom();
            request.setAttribute("totalFreeRoom", totalFreeRoom);
            int totalCar = adminDao.totalCar();
            request.setAttribute("totalCar", totalCar);
            int totalFreeCar = adminDao.totalFreeCar();
            request.setAttribute("totalFreeCar", totalFreeCar);
            int totalUserPayment = adminDao.totalUserPayment();
            request.setAttribute("totalUserPayment", totalUserPayment);
            int totalFreeUserPayment = adminDao.totalFreeUserPayment();
            request.setAttribute("totalFreeUserPayment", totalFreeUserPayment);
            request.getRequestDispatcher("/page/admin/console.jsp").forward(request, response);
            //楼栋管理查询
        } else if ("info".equals(opt)) {
            Admin admin = (Admin) session.getAttribute("admin");
            AdminDesc adminDesc = adminDao.selectAdminDesc(admin.getId());
            session.setAttribute("adminDesc", adminDesc);
            if (adminDesc != null) {
                writer.write(R.success("数据加载成功", adminDesc).toJSON());
            } else {
                writer.write(R.error("数据加载失败").toJSON());
            }
        } else if ("update".equals(opt)) {
            Admin admin = (Admin) session.getAttribute("admin");
            String email = request.getParameter("email");
            String phone = request.getParameter("phone");
            String adminDescId = request.getParameter("adminDescId");
            String nickname = request.getParameter("nickname");
            String job = request.getParameter("job");
            String tags = request.getParameter("tags");
            String content = request.getParameter("content");
            // 修改管理员
            int count = adminDao.updateEmailAndPhone(admin.getId(), email, phone);
            count += adminDao.updateAdminDesc(new AdminDesc(Integer.parseInt(adminDescId), nickname, job, tags, content));
            if (count > 0) {
                writer.write(R.success("更新成功!").toJSON());
            } else {
                writer.write(R.error("更新失败...").toJSON());
            }
        } else if ("view".equals(opt)) {
            // 显示个人中心
            Admin admin = (Admin) session.getAttribute("admin");
            // 加载管理员详情
            admin.setAdminDesc(adminDao.selectAdminDesc(admin.getId()));
            request.setAttribute("admin", admin);
            // 更新Session数据
            session.setAttribute("admin", admin);
            request.getRequestDispatcher("/page/admin/user-setting.jsp").forward(request, response);
        } else if ("updatePwd".equals(opt)) {
            String oldpwd = request.getParameter("oldpwd");
            String newpwd1 = request.getParameter("newpwd1");
            String newpwd2 = request.getParameter("newpwd2");
            Admin admin = (Admin) session.getAttribute("admin");
            String pwd = adminDao.selectPwd();
            String salt = admin.getSalt();
            String newpwd = CodecUtils.md5Hex(newpwd2, salt);
            if (CodecUtils.match(pwd, oldpwd, salt)) {
                if (newpwd1.equals(newpwd2)) {
                    int i = adminDao.updatePwd(newpwd);
                    if (i > 0) {
                        writer.write(R.success("密码修改成功!").toJSON());
                    } else {
                        writer.write(R.success("密码修改失败!").toJSON());
                    }
                } else {
                    writer.write(R.error("两次密码输入不一致").toJSON());
                }
            } else {
                writer.write(R.error("原始密码输入错误!").toJSON());
            }
        } else if ("upload".equals(opt)) {
            try {
                Admin admin = (Admin) session.getAttribute("admin");
                // 上传头像
                // 1.磁盘文件对象工厂
                DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
                // 2.构建上传核心对象ServletFileUpload
                ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory);
                // 2.1.限制文件上传大小 5M
                upload.setFileSizeMax(5 * 1024 * 1024);
                // 3.获得表单FileItem集合(解析表单=普通表单+文件表单)
                List<FileItem> itemList = upload.parseRequest(request);
                String path_img = ""; // 头像地址
                // 4.解析表单获取数据
                for (FileItem fileItem : itemList) {
                    if (!fileItem.isFormField()) { // 上传表单
                        // 5.文件表单(上传)
                        // 5.1.获取服务器路径
                        String realPath = getServletContext().getRealPath("/images");
                        // 5.2.获取文件后缀
                        String fileItemName = fileItem.getName();
                        String ext = StringUtils.substringAfterLast(fileItemName, ".");
                        fileItemName = admin.getUsername() + "." + ext;
                        path_img = "/images/" + fileItemName;
                        fileItem.write(new File(realPath, fileItemName));
                    }
                }
                // 6.更新头像链接
                int count = adminDao.updateAdminImg(admin.getId(), path_img);
                if (count > 0) {
                    writer.write(R.success("上传成功!", path_img).toJSON());
                } else {
                    writer.write(R.error("修改失败...").toJSON());
                }
            } catch (Exception e) {
                writer.write(R.error("上传失败:文件大小超出限制!").toJSON());
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
